<?php

namespace Frieza\Modules\Creators\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Creator\AdmMyRight;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\service\Right\UserRight;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class MyRightController extends Controller
{
    private function getRights()
    {
        $res = [];
        foreach (UserRight::$levelRightMap as $key => $item) {
            $res[$key] = $item['name'];
        }
        return $res;
    }

    public function list(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $search['right_code'] = $request->input('right_code');

        $where = $this->buildWhere($search);
        $total = AdmMyRight::count($where);
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $kvRight = $this->getRights();
        $rights = AdmMyRight::selectByWhere($where);
        if ($rights) {
            //用户分群
            $list = array_column($rights, 'id');
            $userProfiles = AdmOperationModule::getPositionRulesById($list, PositionRules::MODULE_TYPE_CREATORS_MY_RIGHT);
            foreach ($rights as $key => $right) {
                $rights[$key]['user_profile'] = $userProfiles[$right['id']];
                $rights[$key]['right_code'] = $kvRight[$right['right_code']];
                $rights[$key]['icon'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $right['icon'], ImgUrl::IMAGE_SIZE_OP_ORI);
                $link = '';
                if ($right['link']) {
                    $linkArr = json_decode($right['link'], true);
                    $link = $linkArr['link_type'] . $linkArr['link_params']['url'];
                }
                $rights[$key]['link'] = $link;
            }
        }
        $gridModel = new pGridDataModel($rights, $total, ['perPage' => $pageSize]);
        $gridList = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $kvRight) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->filter(function (Filter $filter) use ($kvRight) {
                $filter->disableIdFilter();
                $filter->column(6, function (Filter $filter) use ($kvRight) {
                    $filter->equal('right_code', '权益名称')->select($kvRight);
                });
                $filter->expand();
            });

            $grid->column('id', 'ID');
            $grid->column('right_code', '权益名称');
            $grid->column('icon', '图片地址')->image();
            $grid->column('link', '链接地址');
            $grid->column('remarks', '备注');
            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->column('admin_id', '操作者')->display(function ($operator) {
                return Admin::user()->find($operator)->name;
            });
            $grid->actions(function ($action) {
            });
        });
        $tab = new Tab();
        $tab->add('我的权益', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('我的权益')
            ->description(' ')
            ->breadcrumb(['text' => '我的权益']);
    }

    public function create(Content $content)
    {
        $tab = new Tab();
        $form = new Form();
        $form->select('right_code', '权益名称')->options($this->getRights())->required();
        $form->imgUpload('icon', '图标')->help('图标，必须需要上传');
        $form->multiLinkSelect('link', '跳转链接');
        $form->multiLinkSelect('toast_link', '弹窗链接');
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->text('remarks', '备注');
        $form->action('/admin/creators/myright/save');
        $tab->add('添加权益', $form, true);
        $content->header('添加权益')
            ->breadcrumb(
                ['text' => '我的权益', 'url' => '/creators/myright/list'],
                ['text' => '添加我的权益',]
            )
            ->row($tab);
        return $content;
    }

    public function save(Request $request)
    {
        $params = $request->all();
        if (!empty(AdmMyRight::getByWhere(['right_code' => $params['right_code'], 'status' => AdmMyRight::STATUS_NORMAL]))) {
            $error = new MessageBag([
                'title' => '权益已经存在'
            ]);
        } else {
            $userProfile = $params['user_profile'];
            $params['link'] = !empty($params['link']) ? json_encode($params['link']) : '';
            $params['toast_link'] = !empty($params['toast_link']) ? json_encode($params['toast_link']) : '';
            $data = [
                'status' => AdmMyRight::STATUS_NORMAL,
                'addtime' => time(),
                'edittime' => time(),
                'admin_id' => Admin::user()->id,
                'right_code' => $params['right_code'],
                'icon' => $params['icon'] ?? '',
                'link' => $params['link'],
                'toast_link' => $params['toast_link'],
                'remarks' => $params['remarks'],
            ];
            $id = AdmMyRight::addRights($data);
            //用户分群
            if ($id) {
                AdmOperationModule::addUserProfile($id, $userProfile, PositionRules::MODULE_TYPE_CREATORS_MY_RIGHT);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            if ($id) {
                return redirect('/admin/creators/myright/list')->with(compact('success'));
            }
        }
        return redirect('/admin/creators/myright/list')->with(compact('error'));
    }

    public function edit(Content $content, $id)
    {
        $tab = new Tab();
        $where = ['id' => $id];
        $list = AdmMyRight::get('*', $where);
        $data = [
            'right_code' => $list['right_code'],
            'icon' => $list['icon'],
            'link' => json_decode($list['link'], true),
            'toast_link' => json_decode($list['toast_link'], true),
            'remarks' => $list['remarks'],
            "user_profile" => AdmOperationModule::getPositionRulesById($id, PositionRules::MODULE_TYPE_CREATORS_MY_RIGHT, true)
        ];
        $form = new Form($data);
        $form->select('right_code', '权益名称')->options($this->getRights())->required();
        $form->imgUpload('icon', '图标')->help('图标，必须需要上传');
        $form->multiLinkSelect('link', '跳转链接');
        $form->multiLinkSelect('toast_link', '弹窗链接');
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->text('remarks', '备注');
        $tab->add('修改我的权益', $form, true);
        $form->action('/admin/creators/myright/' . $id . '/update');
        $content->header('我的权益')
            ->breadcrumb(
                ['text' => '我的权益', 'url' => '/creators/myright/list'],
                ['text' => '修改我的权益',]
            )
            ->row($tab);
        return $content;
    }

    public function editSave(Request $request, $id)
    {
        $params = $request->input();
        if (!empty(AdmMyRight::getByWhere(['right_code' => $params['right_code'], 'status' => AdmMyRight::STATUS_NORMAL, 'id[!]' => $id]))) {
            $error = new MessageBag([
                'title' => '权益已经存在'
            ]);

        } else {
            $userProfile = $params['user_profile'];
            $params['link'] = !empty($params['link']) ? json_encode($params['link']) : '';
            $params['toast_link'] = !empty($params['toast_link']) ? json_encode($params['toast_link']) : '';
            $data = [
                'right_code' => $params['right_code'],
                'icon' => $params['icon'],
                'link' => $params['link'],
                'toast_link' => $params['toast_link'],
                'admin_id' => Admin::user()->id,
                'remarks' => $params['remarks']
            ];
            if ($id) {
                $result = AdmMyRight::updateById($data, $id);
                AdmOperationModule::addUserProfile($id, $userProfile, PositionRules::MODULE_TYPE_CREATORS_MY_RIGHT);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            if ($result) {
                return redirect('/admin/creators/myright/list')->with(compact('success'));
            }
        }

        return redirect('/admin/creators/myright/list')->with(compact('error'));
    }

    public function deleteById($id)
    {
        $result = AdmMyRight::deleteById($id);
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        $error = new MessageBag([
            'title' => '操作失败'
        ]);

        if ($result) {
            return redirect('/admin/creators/myright/list')->with(compact('success'));
        }
        return redirect('/admin/creators/myright/list')->with(compact('error'));
    }

    private function buildWhere($search = [])
    {
        $where = [];

        if ($search['right_code']) {
            $where['right_code[~]'] = $search['right_code'];
        }

        $where['status'] = AdmMyRight::STATUS_NORMAL;
        $where['ORDER'] = ['id' => 'DESC'];
        return $where;
    }

}